/*
 * @Author: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @Date: 2021-02-22 18:19:38
 * @LastEditors: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @LastEditTime: 2023-04-13 16:46:28
 * @FilePath: \ant-design-vue-admin-master\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { message } from 'ant-design-vue'
import { toLogin } from '@/utils/common'

export default function () {
  // 创建axios实例
  const instance = axios.create()

  instance.defaults.baseURL = process.env.VUE_APP_BASE_URL
  instance.defaults.timeout = 30 * 1000
  instance.defaults.method = 'post'
  instance.defaults.headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'x-requested-with': 'XMLHttpRequest',
    sysCode: 'csm'
  }
  instance.defaults.withCredentials = true
  window.canCancelAxios = []

  // request拦截器
  instance.interceptors.request.use(
    config => {
      // console.log('config参数====>',config)
      // console.log('config.url', config.url)
      // 拦截白名单
      const whiteList = ['/ihomesacenter/alilogin/gotoswj', '/ihomesacenter/alilogin/bindZaUser'] // 白名单接口
      if (config.url && whiteList.every(item => !config.url.includes(item))) {
        config.cancelToken = new axios.CancelToken(function (c) {
          window.canCancelAxios.push({ key: config.key || '', cancel: c })
        })
      }
      return config
    },
    error => Promise.reject(error)
  )

  // respone拦截器
  instance.interceptors.response.use(
    response => {
      // 拦截业务性接口错误 如果success为false 表示业务性出错
      if (response.data.success || response.data.errorCode === 1) {
        return response.data.result
      } else {
        console.error('报错了')
        // const errCode = `${response.data.errorCode ? `[${response.data.errorCode}]` : ''}`
        message.error(response.data.errorMessage)
        return Promise.reject(response.data.errorMessage)
      }
    },
    error => {
      // 网络不通提示
      if (error.toString() === 'Error: Network Error') {
        message.error('网络出错！')
      }
      // 网络超时
      if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
        message.error('网络请求超时！')
      }
      // 服务器抛错
      if (error.response) {
        console.log('报错提示', error.response)
        const statusCode = error.response.status
        switch (statusCode) {
          case 401:
            toLogin()
            break
          case 404:
            message.error('接口404错误！')
            break
          case 504:
          case 500: // 服务器错误提示
            message.error('服务器出错啦！')
            break
        }
      }
      Promise.resolve(error)
    }
  )
  return instance
}
